package com.zq.it.service.impl.admin;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zq.it.pojo.Teacher;
import com.zq.it.pojo.User;
import com.zq.it.pojo.exam.TClassPaper;
import com.zq.it.pojo.exam.TClassTask;
import com.zq.it.pojo.exam.TCourseWare;
import com.zq.it.pojo.exam.TPaper;
import com.zq.it.pojo.exam.TQuestionDb;
import com.zq.it.pojo.exam.TQuestions;
import com.zq.it.pojo.exam.TStudentTask;
import com.zq.it.pojo.exam.TTask;
import com.zq.it.pojo.exam.TTaskmodel;
import com.zq.it.service.admin.TeacherService;
import com.zq.it.service.common.BaseServiceImpl;
import com.zq.it.service.exam.CourseWareService;
import com.zq.it.service.exam.PaperService;
import com.zq.it.service.exam.QuestionService;
import com.zq.it.service.exam.TaskService;
import com.zq.it.tool.Constant;
import com.zq.it.tool.HeadTitle;

public class TeacherServiceImpl extends BaseServiceImpl implements TeacherService {

	@Override
	public List<Teacher> getAllTeacher() {
		return getTeacherDao().findTeacherEtyList();
	}

	@Override
	public void removeTeacher(Integer id) {
		getTeacherDao().deleteTeacherEtyByID(id);
	}

	@Override
	public void renewalTeacher(Teacher teacher) {
		getTeacherDao().updateTeacherEty(teacher);
	}

	@Override
	public List<Teacher> getTeacher(Integer id) {
		return getTeacherDao().findTeacherEtyById(id);
	}

	@Override
	public List<Teacher> getTeacherListByType(String parameter) {
		parameter = parameter.replaceAll(Constant.Regex.SPACE.toString(), "");
		List list = null;
		String hql = null;
		if (parameter.matches(Constant.Regex.tId.toString()))
			hql = "from Teacher as t where t.teacherId="
					+ Integer.parseInt(parameter);
		else if (parameter.matches(Constant.Regex.tNa.toString()))
			if (!parameter.matches(Constant.Regex.tSex.toString()))
				hql = "from Teacher as t where t.teacherName like '%" + parameter
						+ "%'";
			else {
				if (parameter.equals("男"))
					hql = "from Teacher as t where t.teacherSex=0";
				if (parameter.equals("女"))
					hql = "from Teacher as t where t.teacherSex=1";
			}
		else if (parameter.matches(Constant.Regex.tIdc.toString()))
			hql = ("from Teacher as t where t.teacherIdc like '%" + parameter + "%'");
		if (hql != null)
			list = getTeacherDao().findTeacherByHQL(hql);
		return list;
	}

	@Override
	public List<Teacher> getTeacherByExmp(Teacher teacher) {
		return getTeacherDao().findTeacherEtyByExmp(teacher);
	}

	@Override
	public void removeTeacher(Teacher teacher) {
		getTeacherDao().deleteTeacherEtyByObj(teacher);
	}

	@Override
	public void removeAllTeacher(long[] ids) {
		getTeacherDao().deleteAllEty(ids);
	}

	@Override
	public List<Teacher> importTeacherList(File teacherFile) {
		List<Teacher> teacherList = getTeacherListFromStr(importxlsxFile(teacherFile));
		List<Teacher> existTeacherList = new ArrayList<Teacher>();
		for (int i = 0; i < teacherList.size(); i++) {
			Teacher t = teacherList.get(i);
			if (!getTeacherDao().findTeacherEtyById(t.getTeacherId()).isEmpty())
				existTeacherList.add(t);
		}
		teacherList.removeAll(existTeacherList);
		if (!teacherList.isEmpty()) {
			getTeacherDao().saveTeacherEtyList(teacherList);
			List<User> users = new ArrayList<User>();
			for (Teacher t : teacherList) {
				users.add(new User(t.getTeacherId().toString()));
			}
			getUserDao().saveUserEtyList(users);
		}	
		return existTeacherList;
	}

	private List<Teacher> getTeacherListFromStr(String str) {
		List<Teacher> list = new ArrayList<Teacher>();
		String[] firstArray = str.split(";");
		for (int i = 0; i < firstArray.length; i++) {
			String[] secondArray = firstArray[i].split(":");
			Teacher teacher = new Teacher();
			teacher.setTeacherId(Integer.parseInt(secondArray[0]));
			teacher.setTeacherName(secondArray[1]);
			teacher.setTeacherPassword(secondArray[0]);
			teacher.setTeacherSex(secondArray[2]);
			teacher.setTeacherIdc(secondArray[3]);
			teacher.setDegree(secondArray[4]);
			teacher.setContactWay(secondArray[5]);
			list.add(teacher);
		}
		return list;
	}

	// 数据的导出
	@Override
	public ByteArrayInputStream exportTeacherList(String[] headTitle, List list) {
		return new ByteArrayInputStream(exportToExcel(list, headTitle,
				HeadTitle.EN_TEACHERHEAD.getArray(), "com.zq.it.pojo.Teacher")
						.toByteArray());

	}

	@Override
	public void addTeacher(Teacher teacher) {
		getTeacherDao().save(teacher);
		getUserDao().saveUserEty(new User(teacher.getTeacherId().toString()));
	}
	public Teacher getTeacherByNo(String teacherNo) {
		List data = getTeacherDao().findByTeacherNo(teacherNo);
		if (null != data && !data.isEmpty()) {
			return (Teacher) data.get(0);
		} else {
			return null;
		}

	}

	@Override
	public void updateTeacherImg(Teacher teacher) {
		Teacher newTeacher = getTeacher(teacher.getId());
		newTeacher.setTeacherHead(teacher.getTeacherHead());

		getTeacherDao().update(newTeacher);
	}

	public Teacher getTeacher(long id) {
		return getTeacherDao().findById(id);
	}

	@Override
	public void delete(long[] ids) {
		Teacher teacher = null;
		List temp;
		TCourseWare courseWare;
		TClassPaper classPaper;
		TPaper paper;
		TQuestions question;
		TQuestionDb qdb;
		TClassTask classTask;
		TStudentTask stuTask;
		TTask task;
		TTaskmodel taskModel;
		for (long id : ids) {
			// 删除上传课件
			teacher = getTeacherDao().findById(id);
			temp = courseWareDAO.findByHql(
					"from TCourseWare t where t.TId = " + teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					courseWare = (TCourseWare) temp.get(j);
					Long[] temp2 = {courseWare.getId()};
					((CourseWareService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("courseWareService")).deleteCourseWare(
									temp2, getRealPath(Constant.COURSEWARE),
									teacher);
				}
			}
			// 删除考试相关
			temp = classPaperDAO
					.findByHql("from TClassPaper t where t.TPaper.Teacher.id = "
							+ teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					classPaper = (TClassPaper) temp.get(j);
					String[] temp2 = {classPaper.getId() + ""};
					((PaperService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("paperService"))
									.deleteExamClassList(teacher, temp2);
				}
			}
			temp = paperDAO.findByHql(
					"from TPaper t where t.Teacher.id = " + teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					paper = (TPaper) temp.get(j);
					String[] temp2 = {paper.getId() + ""};
					((PaperService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("paperService")).deletePaper(teacher,
									temp2);
				}
			}
			temp = questionsDAO
					.findByHql("from TQuestions t where t.Teacher.id = "
							+ teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					question = (TQuestions) temp.get(j);
					String[] temp2 = {question.getId() + ""};
					((QuestionService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("questionService")).deleteQuestion(temp2,
									teacher);
				}
			}
			temp = questionsDAO
					.findByHql("from TQuestionDb t where t.Teacher.id = "
							+ teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					qdb = (TQuestionDb) temp.get(j);
					String[] temp2 = {qdb.getId() + ""};
					((QuestionService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("questionService")).deleteQDB(temp2,
									teacher);
				}
			}
			// 删除任务相关
			temp = taskDAO
					.findByHql("from TClassTask t where t.TTask.Teacher.id  = "
							+ teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					classTask = (TClassTask) temp.get(j);
					Long[] temp2 = {classTask.getId()};
					((TaskService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("taskService")).deleteClassTask(teacher,
									temp2);
				}
			}
			temp = taskDAO.findByHql(
					"from TStudentTask t where t.TTask.Teacher.id  = "
							+ teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					stuTask = (TStudentTask) temp.get(j);
					Long[] temp2 = {stuTask.getId()};
					((TaskService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("taskService")).deleteStuTask(teacher,
									temp2);
				}
			}
			temp = taskDAO.findByHql(
					"from TTask t where t.Teacher.id  = " + teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					task = (TTask) temp.get(j);
					Long[] temp2 = {task.getId()};
					((TaskService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("taskService")).deleteTask(teacher, temp2);
				}
			}
			temp = taskDAO.findByHql(
					"from TTaskmodel t where t.uploader  = " + teacher.getId());
			if (temp != null) {
				for (int j = 0; j < temp.size(); j++) {
					taskModel = (TTaskmodel) temp.get(j);
					Long[] temp2 = {taskModel.getId()};
					((TaskService) WebApplicationContextUtils
							.getWebApplicationContext(
									ServletActionContext.getRequest()
											.getSession().getServletContext())
							.getBean("taskService")).deleteTaskModel(temp2,
									getRealPath(Constant.TASKMODEL), teacher);
				}
			}
			deleteDir(new File(
					getRealPath(Constant.HEAD_PIC + teacher.getTeacherHead())));
			getTeacherDao().delete(teacher);
		}
	}

	public Teacher getTeacherByRow(HSSFRow row) {
		Teacher teacher = new Teacher();
		try {

			HSSFDataFormatter hSSFDataFormatter = new HSSFDataFormatter();
			String name = hSSFDataFormatter.formatCellValue(row.getCell(0))
					.trim();
			String sex = hSSFDataFormatter.formatCellValue(row.getCell(1))
					.trim();
			String birth = hSSFDataFormatter.formatCellValue(row.getCell(2))
					.trim();
			String teacherNo = hSSFDataFormatter.formatCellValue(row.getCell(3))
					.trim();
			String degree = hSSFDataFormatter.formatCellValue(row.getCell(4))
					.trim();
			String title = hSSFDataFormatter.formatCellValue(row.getCell(5))
					.trim();
			String email = hSSFDataFormatter.formatCellValue(row.getCell(6))
					.trim();
			teacher.setTeacherName(name);
			if (sex.equals("男"))
				teacher.setTeacherSex("1");
			else if (sex.equals("女"))
				teacher.setTeacherSex("0");
			teacher.setTeacherId(Integer.parseInt(teacherNo));
			teacher.setDegree(degree);
			return teacher;
		} catch (Exception e) {

			return teacher;
		}
	}
}
